# encoding:utf-8
'''
Created on 2020-12-23
@author: adog
ref: https://scikit-learn.org/stable/auto_examples/applications/plot_stock_market.html#sphx-glr-auto-examples-applications-plot-stock-market-py
'''
import apps.adog.dataMan as DM
import util.xtool as xtool
import util.tradeDate as TD
import apps.adog.util.dbcom as dbcom
import apps.adog.util.mdbcom as mdbcom

import numpy as np
import pandas as pd
import json
import chart_studio.plotly
import plotly.graph_objs as graphObj
from datetime import datetime, timedelta
import time
import re

class Memo():
    def __init__(self,user):
        self.user=user
        self.memo=None
        self.tvData=mdbcom.find('jqk_alert',queryDict={'user':user},outType='pandas')
        if len(self.tvData)>0:
            self.tvData['cod']=[re.sub('\d','',self.tvData.loc[i,'symbol'].split(':')[-1]) for i in self.tvData.index ]
            self.future_info=mdbcom.find('future_info',outType='pandas')
            self.future_info.rename(columns={u'保金_原':'marginRate',u'_id':'cod'},inplace=True)
            self.future_info['marginRate']=pd.to_numeric(self.future_info['marginRate'])
            self.future_info['cod']=self.future_info['cod'].astype(str)
            self.tvData=pd.merge(left=self.tvData,right=self.future_info[['cod','marginRate']],on='cod',how='left')
            if len(self.tvData)>0:
                self.tvData.sort_values(by=['chartName','symbol','interval','lastUpdateTimeStr'],
                             ascending=[1,1,1,1],inplace=True)
        
        self.fields=['chartName','symbol','interval','lastUpdateTimeStr','text','marginRate','xtime']
    '''
    def getTvTable(self):
        memo=self.tvData.loc[self.tvData['type']=='memo',self.fields]
        att=self.tvData.loc[self.tvData['type']=='atte',self.fields]
        keyPrice=self.tvData.loc[self.tvData['type']=='keyp',self.fields]
        
        memo_att=pd.merge(left=memo, right=att,on=['chartName','symbol','interval'],how='outer')
        memo_att_keyPrice=pd.merge(left=memo_att, right=keyPrice,on=['chartName','symbol','interval'],how='outer')
    
    def getTable(self,type=None):
        x=self.tvData.loc[self.tvData['type']==type,self.fields]
        #memo.set_index(['chartName','symbol','interval','lastUpdateTimeStr'],inplace=True)
    '''    
    def getMemo(self,keyword='',isSetMultiIndex=True):
        if len(self.tvData)==0:
            return []
        
        memo=self.tvData.loc[self.tvData['type']=='memo',self.fields]
        if keyword!='':
            memo=memo.loc[(memo['chartName'].str.contains(keyword,case=False))|\
                          (memo['symbol'].str.contains(keyword,case=False))|\
                          (memo['text'].str.contains(keyword,case=False)),:]
        if isSetMultiIndex:
            memo.set_index(['chartName','symbol','interval','lastUpdateTimeStr'],inplace=True)
        #tbl=xtool.getHtml(memo,align='left')
        return memo
    
    def getAtt(self,keyword='',isSetMultiIndex=True):
        att=self.tvData.loc[self.tvData['type']=='atte',self.fields]
        if keyword!='':
            att=att.loc[(att['chartName'].str.contains(keyword,case=False))|\
                        (att['symbol'].str.contains(keyword,case=False))|\
                        (att['text'].str.contains(keyword,case=False)),:]
        att['att']=0
        att['cp']=0
        for i in att.index:
            #if i ==279:
            #    print(i)
            try:
                atxt=att.loc[i,'text'].replace('@','').replace('!','').replace('！','').replace('，',',').split(',')
                if len(atxt)==0 or atxt=='':
                    pass
                elif len(atxt)==1:
                    att.loc[i,'cp']=0 if atxt[0]=='' else int(atxt[0]) 
                elif len(atxt)==2:
                    att.loc[i,'att']=0 if atxt[0]=='' else int(atxt[0]) 
                    att.loc[i,'cp']=0 if atxt[1]=='' else int(atxt[1]) 
            except Exception as e:
                print(e)   
        if isSetMultiIndex:
            att.set_index(['chartName','symbol','interval','lastUpdateTimeStr'],inplace=True)
        return att
    
    def getKeyPrices(self,keyword='',isSetMultiIndex=True):
        keyp=self.tvData.loc[self.tvData['type']=='keyp',self.fields+['alarm']]
        if keyword!='':
            keyp=keyp.loc[(keyp['chartName'].str.contains(keyword,case=False))|\
                          (keyp['symbol'].str.contains(keyword,case=False))|\
                          (keyp['text'].str.contains(keyword,case=False)),:]
            
        keyp.drop_duplicates(['chartName','symbol','interval','lastUpdateTimeStr','text'],keep='last',inplace=True)
        if isSetMultiIndex:
            keyp.set_index(['chartName','symbol','interval','lastUpdateTimeStr','text'],inplace=True)
            #tbl=xtool.getHtml(keyp,align='left')
        return keyp
    
    
    def getAttLast(self,keyword='',sortBy='att',top=None):
        att=self.getAtt(keyword=keyword,isSetMultiIndex=False)
        att=att.loc[~att['symbol'].str.contains('8888'),:]
        att.sort_values(by=['chartName','symbol','lastUpdateTimeStr'],
                         ascending=[1,1,1],inplace=True)
        att.drop_duplicates(['chartName', 'symbol'],keep='last',inplace=True)
        #att_plot.reset_index(drop=False,inplace=True)
       
        att['sign']=['+' if att.loc[i,'cp']>=0 else '-' for i in att.index]
        if top is not None:
            if sortBy=='att':
                att=att.loc[att[sortBy].isin(sorted(att[sortBy].unique())[-top:]),:]
            elif sortBy=='cp':
                att=att.loc[att[sortBy].isin(sorted(att[sortBy].unique())[-top:]+sorted(att[sortBy].unique())[:top]),:]
        att.sort_values(by=[sortBy,'marginRate'],
                         ascending=[0,1],inplace=True)
        return att
    
if __name__=='__main__':
    mm=Memo('adog')
    mm.plotAtt()
    
